<?php

namespace App\Kuafu\Order\Model\Clickhouse;

use App\Kuafu\CustomPayment\Model\CustomPaymentModel;
use App\Kuafu\Order\Model\OrderPayUnionSplitModel;
use App\Kuafu\Order\Service\OrderDb;
use App\Kuafu\Pay\Model\Clickhouse\PayStreamCHModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Pay\Model\RefundStreamModel;
use Kuafu\LaravelClickHouse\Database\Eloquent\Model;

class OrderPayUnionCHModel extends Model
{
    protected $connection = 'clickhouseOrderAll';
    protected $table      = 'kf_order_pay_union';

    public function getPayTypeTextAttribute()
    {
        $res = OrderPayUnionSplitModel::PAY_TYPE_TEXT[$this->payType] ?? '';

        switch ($this->payType) {
            case OrderPayUnionSplitModel::PAY_TYPE_FY:
                if ($this->payStatus == OrderPayUnionSplitModel::PAY_STATUS_OK) {
                    $suffix = (string)optional($this->payStreamsRel)->payChannelChildText;
                } else {
                    $suffix = (string)optional($this->refundStreamsRel)->refundChannelChildText;
                }
                return $suffix ? $res . ' - ' . $suffix : $res;
            case $this->payType > OrderPayUnionSplitModel::PAY_TYPE_DEFINE:
                $res    = OrderPayUnionSplitModel::PAY_TYPE_TEXT[OrderPayUnionSplitModel::PAY_TYPE_DEFINE];
                $suffix = (string)optional($this->customPaymentsRel)->name;
                return $suffix ? $res . ' - ' . $suffix : $res;
        }

        return OrderPayUnionSplitModel::PAY_TYPE_TEXT[$this->payType] ?? '';
    }

    public function getPayStatusTextAttribute()
    {
        return OrderPayUnionSplitModel::PAY_STATUS_TEXT[$this->payStatus] ?? '';
    }

    public function customPaymentsRel()
    {
        return $this->hasOne(CustomPaymentModel::class, 'id', 'payType');
    }

    public function payStreamsRel()
    {
        return $this->hasOne(PayStreamCHModel::class, 'payNo', 'bizId');
    }

    public function refundStreamsRel()
    {
        return $this->hasOne(RefundStreamModel::class, 'refundNo', 'bizId');
    }
}
